package com.itheima.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        //需要被放行的请求
        String[] urls = {
                "/login.do",
                "/login.html",
                "/css/**",
                "/elementuidemo/**",
                "/img/**",
                "/js/**",
                "/plugins/**",
                "/template/**",
                "/checkgroup/*",
                "/setmeal/**"
        };
        //循环判断请求是否满足放行要求
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                System.out.println("此请求被放行");
                filterChain.doFilter(request, response);
                return;
            }
        }
        //4.1 获得用户登录信息
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null) {//代表没有登录，正常拦截跳转到登录页面
            //5、如果未登录则返回未登录结果  跳转登录页面
            response.sendRedirect("/login.html");
            return;
        }
        filterChain.doFilter(request, response);
        return;
    }
}
